package com.fluagen.client.lsp.api;

import java.util.UUID;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.handler.BodyHandler;

public class ClientAPIVerticle extends AbstractVerticle {

	private static final String HOST = "0.0.0.0";
	private static final int PORT = 8082;

	private static final Logger log = LoggerFactory.getLogger(ClientAPIVerticle.class);

	WebClient client;

	@Override
	public void start(Future<Void> future) throws Exception {
		client = WebClient.create(vertx);

		Router router = Router.router(vertx);
		router.route("/*").handler(BodyHandler.create());

		router.get("/loginp").handler(this::loginp);
		router.get("/demo1").handler(this::postDemo);

		JsonObject config = context.config();

		vertx.createHttpServer().requestHandler(router::accept).listen(config.getInteger("http.port", PORT),
				config.getString("http.address", HOST), result -> {
					if (result.succeeded()) {
						future.complete();
						log.info("ClientAPIVerticle start");

					} else {
						future.fail(result.cause());
					}

				});
	}

	private void loginp(RoutingContext context) {

		HttpServerRequest request = context.request();
		HttpServerResponse response = context.response();

		JsonObject body = new JsonObject();

		request.params().forEach(e -> {
			body.put(e.getKey(), e.getValue());
		});
		body.put("userId", "zhangsan");
		body.put("username", "zhangsan");

		String cbURL = body.getString("lp_uri");
		// body.remove("lp_uri");

		log.info("CLSP response return token to :" + cbURL);

		response.putHeader("location", cbURL).putHeader("X-Okapi-Token", UUID.randomUUID().toString())
				.setStatusCode(302).end(body.toString());

	}

	private void postDemo(RoutingContext context) {
		// client.post(80, "www.baidu.com", "/")
		// .sendJsonObject(new JsonObject().put("firstName",
		// "Dale").put("lastName", "Cooper"), ar -> {
		// if (ar.succeeded()) {
		// log.info(ar.result());
		// } else {
		// log.info(ar.cause().getMessage());
		// }
		// });

		client.get(80, "http://www.baidu.com", "").send(ar -> {
			if (ar.succeeded()) {
				log.info(ar.result());
			} else {
				log.info(ar.cause().getMessage());
			}
		});
	}
}
